package com.ft.f_springboot_route.service.impl;


import com.ft.f_springboot_route.bean.Banner;
import com.ft.f_springboot_route.mapper.BannerMapper;
import com.ft.f_springboot_route.service.BannerService;
import com.ft.f_springboot_route.utils.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;


@Service
public class BannerServiceImpl implements BannerService {
    @Autowired
    private BannerMapper bannerMapper;
    @Override
    public Pager<Banner> selectBannerAll(Integer routeId, Integer currentPage) {
            Pager<Banner> bannerPager=new Pager<>();
            bannerPager.setCurrentPage(currentPage);

            bannerPager.setPageSize(2);

            bannerPager.setList(bannerMapper.selectBannerAll(routeId, (currentPage-1)*2));

            bannerPager.setTotal(selectBannerTotal(routeId));

        return bannerPager;
    }

    @Override
    public Long selectBannerTotal(Integer routeId) {
        return bannerMapper.selectBannerTotal(routeId);
    }

    @Override
    public Banner selectBannerById(Integer banId) {
        return bannerMapper.selectBannerById(banId);
    }

    @Override
    public void addBanner(Banner banner) {
        bannerMapper.addBanner(banner);
    }

    @Override
    public void editBannerById(Banner banner) {
        bannerMapper.editBannerById(banner);
    }

    @Override
    public void deleteBannerById(Integer banId) {

        deleteBannerFile(banId);
        bannerMapper.deleteBannerById(banId);

    }

    @Override
    public void deleteBannerByRouteId(Integer routeId) {
        deleteBannerFileByRouteId(routeId);
        bannerMapper.deleteBannerByRouteId(routeId);
    }

    @Override
    public List<Banner> selectBannerByRouteId(Integer routeId) {
        return bannerMapper.selectBannerByRouteId(routeId);
    }


    public void deleteBannerFileByRouteId(Integer routeId){
        List<Banner> banners = selectBannerByRouteId(routeId);
        for (Banner banner : banners) {
            String banSrc = banner.getBanSrc();
            File file=new File("e:/uploads/"+banSrc);
            if(file.exists()) {
                file.delete();
            }
        }
    }


    public void deleteBannerFile(Integer banId){
        Banner banner = selectBannerById(banId);
        String banSrc = banner.getBanSrc();
        File file=new File("e:/uploads/"+banSrc);
        if(file.exists()) {
            file.delete();
        }
    }
}
